package com.message.ui.sys.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.message.ui.sys.dao.AdminUserDao;
import com.message.ui.sys.pojo.AdminUser;
import com.message.ui.sys.service.AdminUserService;
import com.message.ui.sys.utils.AdminUserUtil;
import com.system.comm.model.Page;
import com.system.comm.utils.FrameNoUtil;
import com.system.comm.utils.FrameStringUtil;
import com.system.comm.utils.FrameTimeUtil;
import com.system.handle.model.ResponseCode;
import com.system.handle.model.ResponseFrame;

/**
 * admin_user的Service
 * @author autoCode
 * @date 2017-12-27 15:24:05
 * @version V1.0.0
 */
@Component
public class AdminUserServiceImpl implements AdminUserService {

	@Autowired
	private AdminUserDao adminUserDao;
	
	@Override
	public ResponseFrame saveOrUpdate(AdminUser adminUser) {
		ResponseFrame frame = new ResponseFrame();
		if(FrameStringUtil.isEmpty(adminUser.getId())) {
			adminUser.setId(FrameNoUtil.uuid());
			adminUser.setCreateTime(FrameTimeUtil.getTime());
			adminUser.setPassword(AdminUserUtil.encodePassword(adminUser.getPassword()));
			adminUserDao.save(adminUser);
		} else {
			if(FrameStringUtil.isNotEmpty(adminUser.getPassword())) {
				adminUser.setPassword(AdminUserUtil.encodePassword(adminUser.getPassword()));
			}
			adminUserDao.update(adminUser);
		}
		frame.setCode(ResponseCode.SUCC.getCode());
		return frame;
	}

	@Override
	public AdminUser get(String id) {
		return adminUserDao.get(id);
	}

	@Override
	public ResponseFrame pageQuery(AdminUser adminUser) {
		adminUser.setDefPageSize();
		ResponseFrame frame = new ResponseFrame();
		int total = adminUserDao.findAdminUserCount(adminUser);
		List<AdminUser> data = null;
		if(total > 0) {
			data = adminUserDao.findAdminUser(adminUser);
		}
		Page<AdminUser> page = new Page<AdminUser>(adminUser.getPage(), adminUser.getSize(), total, data);
		frame.setBody(page);
		frame.setCode(ResponseCode.SUCC.getCode());
		return frame;
	}
	
	@Override
	public ResponseFrame delete(String id) {
		ResponseFrame frame = new ResponseFrame();
		adminUserDao.delete(id);
		frame.setCode(ResponseCode.SUCC.getCode());
		return frame;
	}

	@Override
	public ResponseFrame login(AdminUser adminUser) {
		ResponseFrame frame = new ResponseFrame();
		AdminUser user = getByUsername(adminUser.getUsername());
		if(user == null) {
			//不存在用户
			frame.setCode(-2);
			frame.setMessage("请输入正确的用户和密码!");
			return frame;
		}
		if(!AdminUserUtil.encodePassword(adminUser.getPassword()).equalsIgnoreCase(user.getPassword())) {
			//密码不正确
			frame.setCode(-2);
			frame.setMessage("请输入正确的用户和密码!");
			return frame;
		}
		//密码相同
		frame.setBody(user);
		frame.setSucc();
		return frame;
	}

	private AdminUser getByUsername(String username) {
		return adminUserDao.getByUsername(username);
	}
}